<template>
  <div class="email-app">
    <h1>邮件系统</h1>

    <!-- 邮件列表区域 -->
    <div class="email-list-container">
      <div class="email-controls">
        <button @click="deleteSelectedEmails" :disabled="!hasSelectedEmails">删除选中</button>
        <button @click="deleteAllEmails" :disabled="emails.length === 0">全部清空</button>
        <div class="email-stats">总计: {{ emails.length }} 封 | 未读: {{ unreadCount }} 封</div>
      </div>

      <!-- 邮件列表标题栏 -->
      <div class="email-header">
        <div class="col-selector">
          <input type="checkbox" v-model="selectAll" @change="handleSelectAll" />
        </div>
        <div class="col-subject">主题</div>
        <div class="col-sender">发件人</div>
        <div class="col-date">日期</div>
        <div class="col-action">操作</div>
      </div>

      <!-- 邮件列表 -->
      <div class="email-items">
        <div
          v-for="email in emails"
          :key="email.id"
          class="email-item"
          :class="{ read: email.isRead }"
          @click="openEmailDetail(email)"
        >
          <div class="col-selector">
            <input type="checkbox" v-model="email.selected" @click.stop="handleSelectChange" />
          </div>
          <div class="col-subject">
            <div class="subject-text">{{ email.subject }}</div>
            <div class="excerpt-text">{{ email.content.substring(0, 80) }}...</div>
          </div>
          <div class="col-sender">{{ email.sender }}</div>
          <div class="col-date">{{ formatDate(email.timestamp) }}</div>
          <div class="col-action">
            <button class="delete-btn" @click.stop="deleteSingleEmail(email.id)">删除</button>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-if="emails.length === 0" class="empty-state">没有收到任何邮件</div>
      </div>
    </div>

    <!-- 邮件详情模态框 -->
    <div v-if="currentEmail" class="modal-overlay" @click="closeEmailDetail">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ currentEmail.subject }}</h2>
          <button class="close-btn" @click="closeEmailDetail">&times;</button>
        </div>
        <div class="modal-body">
          <div class="email-info-bar">
            <div class="info-item">
              <span class="info-label">发件人:</span>
              <span class="info-value">{{ currentEmail.sender }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">发送时间:</span>
              <span class="info-value">{{ formatDate(currentEmail.timestamp) }}</span>
            </div>
            <div class="info-item" v-if="!currentEmail.isRead">
              <span class="unread-badge">未读</span>
            </div>
          </div>
          <hr />
          <div class="email-full-content">{{ currentEmail.content }}</div>
        </div>
        <div class="modal-footer">
          <button @click="toggleReadStatus" class="read-status-btn">
            {{ currentEmail.isRead ? '标记为未读' : '标记为已读' }}
          </button>
          <button @click="deleteCurrentEmail" class="delete-btn">删除此邮件</button>
          <button @click="closeEmailDetail">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { type Email } from '@/model/message'
import {
  apiDeleteAllEmails,
  apiDeleteMultipleEmails,
  apiDeleteSingleEmail,
  apiGetAllEmails,
  apiMarkAsRead,
} from '@/api/message'

interface EmailModel extends Email {
  selected: boolean
}

export default {
  data() {
    return {
      // 所有邮件发件人统一为管理员 admin@example.com
      emails: [
        {
          id: 1,
          subject: '欢迎使用系统通知服务',
          sender: 'admin@example.com', // 管理员邮箱
          content:
            '尊敬的用户，欢迎使用本系统的邮件通知服务！\n\n今后系统相关的重要通知、操作提醒等都会通过此邮箱发送给您，请定期查看以获取最新信息。\n\n如有使用问题，可通过系统反馈功能联系我们。',
          timestamp: new Date('2025-10-20').getTime(),
          isRead: true,
          selected: false,
        },
        {
          id: 2,
          subject: '系统升级维护通知',
          sender: 'admin@example.com', // 管理员邮箱
          content:
            '尊敬的用户，为提升系统性能和安全性，我们将于本周末进行系统升级维护，具体安排如下：\n- 维护时间：2025-10-26 00:00 - 06:00\n- 影响范围：维护期间可能无法正常使用部分功能\n- 注意事项：请提前保存好您的操作数据，避免数据丢失\n\n给您带来的不便，敬请谅解！',
          timestamp: new Date('2025-10-22').getTime(),
          isRead: false,
          selected: false,
        },
        {
          id: 3,
          subject: '您的账户安全提醒',
          sender: 'admin@example.com', // 管理员邮箱
          content:
            '尊敬的用户，我们检测到您的账户于2025-10-23 15:30在新设备（IP: 123.123.123.123）上登录。\n\n若此操作是您本人所为，无需额外操作；若不是您本人操作，请立即修改密码并通过系统安全中心锁定账户，或联系管理员协助处理。\n\n请务必保护好您的账户信息，避免泄露。',
          timestamp: new Date('2025-10-23').getTime(),
          isRead: false,
          selected: false,
        },
        {
          id: 4,
          subject: '新功能上线通知',
          sender: 'admin@example.com', // 管理员邮箱
          content:
            '尊敬的用户，系统已上线「消息归档」新功能！\n\n功能说明：您可以将重要邮件手动归档至「归档文件夹」，归档后的邮件不会出现在默认列表中，但可通过「归档」入口查看，帮助您更好地整理邮件内容。\n\n使用路径：邮件详情页 → 右上角「归档」按钮\n\n如有功能使用疑问，可查看系统帮助文档或联系管理员。',
          timestamp: new Date('2025-10-24').getTime(),
          isRead: true,
          selected: false,
        },
      ] as EmailModel[],
      currentEmail: null as EmailModel | null, // 当前查看的邮件
      selectAll: false, // 全选状态
    }
  },
  computed: {
    // 检查是否有选中的邮件
    hasSelectedEmails() {
      return this.emails.some((email) => email.selected)
    },
    // 未读邮件数量
    unreadCount() {
      return this.emails.filter((email) => !email.isRead).length
    },
  },
  watch: {
    // 监听选中状态变化，更新全选框
    emails: {
      deep: true,
      handler() {
        this.selectAll = this.emails.length > 0 && this.emails.every((email) => email.selected)
      },
    },
  },
  methods: {
    /**
     * 格式化日期显示
     * @param {Number} timestamp - 时间戳
     * @returns {String} 格式化后的日期字符串
     */
    formatDate(timestamp: number) {
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      })
    },

    /**
     * 处理全选状态变化
     */
    handleSelectAll() {
      this.emails.forEach((email) => {
        email.selected = this.selectAll
      })
    },

    /**
     * 处理邮件选中状态变化
     */
    handleSelectChange() {
      // 由watch监听自动更新全选状态
    },

    /**
     * 打开邮件详情
     * @param {Object} email - 邮件对象
     */
    openEmailDetail(email: EmailModel) {
      this.currentEmail = { ...email }
      // 如果是未读邮件，标记为已读
      if (!email.isRead) {
        this.markAsRead(email.id, true)
      }
    },

    /**
     * 关闭邮件详情
     */
    closeEmailDetail() {
      this.currentEmail = null
    },

    /**
     * 切换邮件已读状态
     */
    toggleReadStatus() {
      if (this.currentEmail) {
        const newStatus = !this.currentEmail.isRead
        this.currentEmail.isRead = newStatus
        this.markAsRead(this.currentEmail.id, newStatus)
      }
    },

    /**
     * 标记邮件为已读/未读
     * @param {Number} id - 邮件ID
     * @param {Boolean} isRead - 是否已读
     */
    markAsRead(id: number, isRead: boolean) {
      const email = this.emails.find((item) => item.id === id)
      if (email) {
        email.isRead = isRead
        // 调用后端接口更新状态
        apiMarkAsRead(id, isRead)
      }
    },

    /**
     * 删除单封邮件
     * @param {Number} id - 邮件ID
     */
    deleteSingleEmail(id: number) {
      if (confirm('确定要删除这封邮件吗？')) {
        // 先更新本地状态
        this.emails = this.emails.filter((email) => email.id !== id)
        // 如果删除的是当前查看的邮件，关闭详情
        if (this.currentEmail && this.currentEmail.id === id) {
          this.closeEmailDetail()
        }
        // 调用后端接口
        apiDeleteSingleEmail(id)
      }
    },

    /**
     * 删除当前查看的邮件
     */
    deleteCurrentEmail() {
      if (this.currentEmail) {
        this.deleteSingleEmail(this.currentEmail.id)
      }
    },

    /**
     * 删除选中的邮件
     */
    deleteSelectedEmails() {
      if (confirm('确定要删除选中的邮件吗？')) {
        const selectedIds = this.emails.filter((email) => email.selected).map((email) => email.id)

        // 先更新本地状态
        this.emails = this.emails.filter((email) => !email.selected)
        // 如果当前查看的邮件被删除，关闭详情
        if (this.currentEmail && selectedIds.includes(this.currentEmail.id)) {
          this.closeEmailDetail()
        }
        // 调用后端接口
        apiDeleteMultipleEmails(selectedIds)
      }
    },

    /**
     * 删除所有邮件
     */
    deleteAllEmails() {
      if (confirm('确定要删除所有邮件吗？此操作不可恢复！')) {
        // 先更新本地状态
        this.emails = []
        // 关闭邮件详情
        this.closeEmailDetail()
        // 调用后端接口
        apiDeleteAllEmails()
      }
    },
  },
  mounted() {
    // 组件挂载时获取仅管理员发送的邮件列表
    apiGetAllEmails()
  },
}
</script>

<style scoped>
.email-app {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.email-app h1 {
  color: #2c3e50;
  margin-bottom: 25px;
  font-weight: 600;
}

/* 邮件列表容器 */
.email-list-container {
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 控制栏 */
.email-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e1e4e8;
}

.email-controls button {
  padding: 6px 14px;
  font-size: 14px;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s;
}

.email-controls button:hover {
  background-color: #0069d9;
}

.email-controls button:disabled {
  background-color: #c8ced3;
  cursor: not-allowed;
}

.email-stats {
  color: #6c757d;
  font-size: 14px;
}

/* 邮件列表标题栏 */
.email-header {
  display: flex;
  padding: 12px 20px;
  background-color: #f1f3f5;
  border-bottom: 1px solid #e1e4e8;
  font-weight: 600;
  color: #495057;
  font-size: 14px;
}

/* 列布局 */
.col-selector {
  width: 50px;
  flex-shrink: 0;
}

.col-subject {
  flex-grow: 1;
  min-width: 400px;
}

.col-sender {
  width: 220px;
  flex-shrink: 0;
}

.col-date {
  width: 180px;
  flex-shrink: 0;
  text-align: right;
}

.col-action {
  width: 80px;
  flex-shrink: 0;
  text-align: center;
}

/* 邮件项 */
.email-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #e1e4e8;
  cursor: pointer;
  transition: background-color 0.15s;
}

.email-item:last-child {
  border-bottom: none;
}

.email-item:hover:not(.read) {
  background-color: #f8f9fa;
}

.email-item.read {
  background-color: #f8f9fa;
  color: #6c757d;
}

.subject-text {
  font-weight: 500;
  margin-bottom: 4px;
}

.excerpt-text {
  font-size: 13px;
  color: #6c757d;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 删除按钮 */
.delete-btn {
  padding: 4px 10px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 3px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.delete-btn:hover {
  background-color: #c82333;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6c757d;
  border-bottom: 1px solid #e1e4e8;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 1000px;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  position: relative;
}

.modal-header {
  padding: 18px 25px;
  border-bottom: 1px solid #e1e4e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: #f1f3f5;
  color: #343a40;
}

.modal-body {
  padding: 25px;
  line-height: 1.7;
}

/* 邮件详情信息栏 */
.email-info-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 25px;
  margin-bottom: 20px;
  font-size: 14px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 600;
  margin-right: 8px;
  color: #495057;
}

.info-value {
  color: #212529;
}

.unread-badge {
  background-color: #007bff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.email-full-content {
  margin-top: 20px;
  color: #212529;
  font-size: 15px;
  white-space: pre-line; /* 保留换行符 */
}

.modal-footer {
  padding: 18px 25px;
  border-top: 1px solid #e1e4e8;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background-color: #f8f9fa;
}

.modal-footer button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s;
}

.read-status-btn {
  background-color: #28a745;
  color: white;
}

.read-status-btn:hover {
  background-color: #218838;
}

.modal-footer .delete-btn {
  padding: 8px 16px;
  font-size: 14px;
}

/* 复选框样式优化 */
input[type='checkbox'] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}
</style>
